package com.task.base;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import com.task.base.util.RunScript;

public class MemoryUseInfo {
    String total = null;

    String buffer = null;

    String cache = null;
    
    String memUsed = null;

    String cpuUsed = null;

    String free = null;
    
    long cpuTime = 0;    
    
    long usageTime = 0;

    public boolean exeFree(ActivityManager am) {
        MemoryInfo memInfo = new MemoryInfo();
        am.getMemoryInfo(memInfo);
        free = new Long(memInfo.availMem/1024).toString();
        String strFree = RunScript.runIt("cat /proc/meminfo");
        if (strFree == null) {
            return false;
        }
       // Log.i("ResourceUseInfo", "cat /proc/meminfo: \n"+strFree);
        String[] lines = strFree.split("\n");       
        String[] t = lines[0].split("[\\s]+");
        total = t[1];
        buffer = lines[2].split("[\\s]+")[1];
        cache = lines[3].split("[\\s]+")[1];
        return true;

    }

    public boolean exeTop() {
        String strTop = RunScript.runIt("top -n 1");
        if (strTop == null) {
            return false;
        }
        //Log.i("ResourceUseInfo", "top -n 1: \n"+strTop);
        String[] lines = strTop.split("\n");
        Integer cpuTotal = 0;
        for (int i = 7; i < lines.length; i++) {                   
            String strLine = lines[i];           
            int index2 = strLine.indexOf("%");
            String per = strLine.substring(index2-2,index2);     
            if(per.charAt(0) == ' '){
                per = per.substring(1);
            }
            cpuTotal = cpuTotal + Integer.parseInt(per);            
            if (cpuTotal >= 100) {
                cpuTotal = 99;
            }            
        } 
        cpuUsed = cpuTotal.toString();
        return true;
    }
    public boolean exeProcStat(){
        String strStat = RunScript.runIt("cat /proc/stat");
        if (strStat == null) {
            return false;
        }
        String[] lines = strStat.split("\n");
        String[] t = lines[0].split("[\\s]+");
        int len = t.length;
        cpuTime = 0;
        long idleTime = Long.parseLong(t[4]);
        for(int i=1;i<len;i++){
            String strTime = t[i];
            cpuTime = cpuTime+ Long.parseLong(strTime);                     
        }
        usageTime = cpuTime - idleTime;
        
        return true;
    }

    class FreeRow {
        String total = null;

        String used = null;

        String free = null;
        
        String buffer = null;
        
        String cache = null;
    }
}
